package com.hsy.sunflowerbao.base.ui.activity

import android.Manifest
import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.DialogInterface
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.support.annotation.NonNull
import android.support.v4.content.res.ResourcesCompat
import com.flux.action.RxStoreChange
import com.flux.dispatcher.RxViewDispatch

import com.flux.ui.activity.FBaseActivityWithToolbar
import com.flux.utils.LogUtil
import com.gyf.barlibrary.ImmersionBar
import com.hsy.sunflowerbao.Application
import com.hsy.sunflowerbao.R
import com.hsy.sunflowerbao.base.action.RequestCode
import com.hsy.sunflowerbao.base.store.BaseStore
import com.hsy.sunflowerbao.utils.CommonUtils
import com.hsy.sunflowerbao.utils.FileUtil

import permissions.dispatcher.NeedsPermission
import permissions.dispatcher.OnNeverAskAgain
import permissions.dispatcher.OnPermissionDenied
import permissions.dispatcher.RuntimePermissions
import java.io.File

/**
 * 基础ToolbarActivity
 * Created on 2017/12/4.
 *
 * @author Yang
 */
@RuntimePermissions
abstract class BaseActivityWithToolbar<T : BaseStore> : FBaseActivityWithToolbar(), RxViewDispatch {

    protected val dispatcher = Application.instance.rxFlux.dispatcher
    protected val manager = Application.instance.rxFlux.subscriptionManager
    protected abstract var store: T

    /**
     * 拍照缓存文件
     */
    protected lateinit var tempFile: File

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val color = ResourcesCompat.getColor(resources, R.color.colorPrimary, null)
        toolbar.setBackgroundColor(color)
        setTitleTextAppearance(R.style.style_title)
        if (!setNavigationIcon()) toolbar.setNavigationIcon(R.drawable.icon_back)
        if (!setNavigationListener()) toolbar.setNavigationOnClickListener { _ ->
            if (!onNavigationClicked()) onBackPressed()
        }

        setStatusBar()
        store.register()
        dispatcher.subscribeRxView(this)
    }

    /**
     * 设置状态栏颜色
     */
    protected open fun setStatusBar() {
        ImmersionBar.with(this)
                .statusBarColor(R.color.colorPrimary)//设置状态栏颜色
                .statusBarDarkFont(false)//设置状态栏文字颜色
                .init()
    }

    open protected fun setNavigationIcon(): Boolean {
        return false
    }

    open protected fun setNavigationListener(): Boolean {
        return false
    }

    open fun onNavigationClicked(): Boolean {
        return false
    }

    override fun onStop() {
        super.onStop()
        store.handleSuper = false
        CommonUtils.hideProgressDialog()
    }

    override fun onStart() {
        super.onStart()
        store.handleSuper = true
    }

    override fun onDestroy() {
        super.onDestroy()
        System.gc()

        unSubscribeDispatcher()
    }

    private fun unSubscribeDispatcher() {
        store.unregister()
        dispatcher.unsubscribeRxView(this)
    }

    /**
     * startActivity
     *
     * @param cls    目标类
     * @param extras 附加参数
     */
    override fun startActivityWithTaskCleared(cls: Class<*>, vararg extras: String) {
        unSubscribeDispatcher()
        super.startActivityWithTaskCleared(cls, *extras)
    }

    /**
     * 网络请求失败处理
     * @param change 数据变动
     */
    override fun onRxStoreChanged(@NonNull change: RxStoreChange) {
        if (store.handleSuper && change.storeId == BaseStore.ID) {
            val msg = if (store.msgRes != -1) getString(store.msgRes)
            else store.msg
            LogUtil.e("Http Error: $msg")
            if (store.needReLogin) {
                CommonUtils.showAuthFailureDialog(this, msg)
            } else {
                showToast(msg)
            }
        }
    }

    override fun getRxTag(): String {
        return javaClass.simpleName
    }

    /**
     * 显示列表对话框
     * @param items    列表项
     * @param listener 点击监听
     */
    protected fun showListDialog(items: Array<String>, listener: (dialog: DialogInterface, which: Int) -> Unit) {
        AlertDialog.Builder(this)
                .setItems(items, listener)
                .setCancelable(true)
                .show()
                .setCanceledOnTouchOutside(true)
    }
    /**
     * 调用相机拍照
     */
    @NeedsPermission(Manifest.permission.CAMERA)
    fun showCamera() {
        val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        tempFile = FileUtil.getImageCacheFile(this, ".jpg")
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile))
        startActivityForResult(intent, RequestCode.ImgTake)
    }

    /**
     * 获取相机权限失败
     */
    @OnPermissionDenied(Manifest.permission.CAMERA)
    internal fun showDeniedForCamera() {
        showToast(getString(R.string.permission_denied, "拍摄"))
    }

    /**
     * 禁止再次获取存储权限
     */
    @OnPermissionDenied(Manifest.permission.READ_EXTERNAL_STORAGE)
    internal fun showDeniedForStorage() {
        showToast(getString(R.string.permission_denied, "存储"))
    }

    /**
     * 禁止再次获取相机权限
     */
    @OnNeverAskAgain(Manifest.permission.CAMERA)
    internal fun showNeverAskForCamera() {
        showToast(getString(R.string.permission_no_ask, "拍摄"))
    }

    /**
     * 禁止再次获取存储权限
     */
    @OnNeverAskAgain(Manifest.permission.READ_EXTERNAL_STORAGE)
    internal fun showNeverAskForStorage() {
        showToast(getString(R.string.permission_no_ask, "存储"))
    }

    /**
     * 权限获取结果
     *
     * @param requestCode  请求码
     * @param permissions  申请的权限
     * @param grantResults 结果
     */
    @SuppressLint("NeedOnRequestPermissionsResult")
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        onRequestPermissionsResult(requestCode, grantResults)
    }
}